package com.crr.mall.product.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.crr.mall.common.utils.Assert;
import com.crr.mall.product.dao.CategoryBrandRelationDao;
import com.crr.mall.product.util.RedisUtils;
import com.crr.mall.product.vo.Catalog2VO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crr.mall.common.utils.PageUtils;
import com.crr.mall.common.utils.Query;

import com.crr.mall.product.dao.CategoryDao;
import com.crr.mall.product.entity.CategoryEntity;
import com.crr.mall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    CategoryDao categoryDao;
    @Autowired
    CategoryBrandRelationDao categoryBrandRelationDao;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<Map> queryTree(int parentId) {
        //加入缓存  缓存中存的是JSON字符串
        String key = redisTemplate.opsForValue().get("catalogJson");
        if (StringUtils.isEmpty(key)) {
            //缓存中没有数据 查询数据库
            List<Map> list = categoryDao.queryTree(parentId);
            String s = JSON.toJSONString(list);
            //查询到的数据放入缓存
            redisTemplate.opsForValue().set("catalogJson", s);
            return list;
        }
        //缓存中存在 转换类型直接返回
        List<Map> result = JSON.parseObject(key, new TypeReference<List<Map>>() {
        });
        return result;
    }

    @Override
    public int removeMenusByIds(List<Long> ids) {
        return baseMapper.deleteByIds(ids);
    }

    @Cacheable(value = {"category"},key = "'catelogLevel'")
    @Override
    public List<CategoryEntity> queryLevelByOne() {
        System.out.println("方法调用");
        return baseMapper.queryLevelByOne(1L);
    }

    @Override
    public List<CategoryEntity> queryByOneId(List<Long> ids) {
        return baseMapper.queryByOneId(ids);
    }

    @Override
    public Map<String, List<Catalog2VO>> getCatalogJSON() {
        /*
        将数据库的多次查询变成一次
        一次性查询出所有数据
        */
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //查出所有一级分类
        List<CategoryEntity> categoryEntities = queryLevelByOne();
        //封装数据
        Map<String, List<Catalog2VO>> parent_cid = categoryEntities.stream().collect(Collectors.toMap(k ->
                k.getCatId().toString(), v -> {
            //每个一级分类里面的所有二级分类
            List<CategoryEntity> categoryEntities1 = getParentCid(selectList, v.getCatId());
            //封装结果
            List<Catalog2VO> catalog2VOS = null;
            if (categoryEntities1 != null) {
                catalog2VOS = categoryEntities1.stream().map(l2 -> {
                    Catalog2VO catalog2VO = new Catalog2VO(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //找当前二级分类的三级分类
                    List<CategoryEntity> category3Entities = getParentCid(selectList, l2.getCatId());
                    if (category3Entities != null) {
                        List<Catalog2VO.Catalog3VO> collect = category3Entities.stream().map(l3 -> {
                            Catalog2VO.Catalog3VO catalog3VO = new Catalog2VO.Catalog3VO(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catalog3VO;
                        }).collect(Collectors.toList());
                        catalog2VO.setCatalog3list(collect);

                    }
                    return catalog2VO;
                }).collect(Collectors.toList());
            }

            return catalog2VOS;
        }));
        return parent_cid;
    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> selectList, Long parentId) {
        List<CategoryEntity> collect = selectList.stream().filter(item ->
                item.getParentCid() == parentId).collect(Collectors.toList());
        return collect;

//        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", parentId);
    }

    /**
     * 分类信息修改 级联的分类品牌关联表修改
     *
     * @param entity
     * @return
     */
    @CacheEvict(value = {"category"},key = "'catelogLevel'")
    @Transactional
    @Override
    public boolean updateById(CategoryEntity entity) {
        boolean b = super.updateById(entity);
        Assert.fail(b, "修改分类信息失败");
        if (null != entity.getName()) {
            int i = categoryBrandRelationDao.updateCategoryNameByCategoryId(entity.getCatId(), entity.getName());
            Assert.fail(i >= 1, "修改分类品牌关联信息失败");
        }
        return true;
    }

}